/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.api.request.ProductIdListRequest;
import com.yami.shop.api.response.OrderResponse;
import com.yami.shop.api.response.OrderShipmentResponse;
import com.yami.shop.bean.app.dto.ProductDto;
import com.yami.shop.bean.app.dto.TagProductDto;
import com.yami.shop.bean.app.param.CreateOrderRequest;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.util.Json;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/prod")
@Api(tags = "商品接口")
public class ProdController {

    @Autowired
    private ProductService prodService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private SkuService skuService;

    @Autowired
    private TransportService transportService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private DeliveryService deliveryService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 订单发货状态，1：待发货，2：部分发货，3：全部发货
     */
    private static String status1 = "1";
    private static String status2 = "2";
    private static String status3 = "3";


    @GetMapping("/pageProd")
    @ApiOperation(value = "通过分类id商品列表信息", notes = "根据分类ID获取该分类下所有的商品列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类ID", required = true, dataType = "Long"),
    })
    public ResponseEntity<IPage<ProductDto>> prodList(
            @RequestParam(value = "categoryId") Long categoryId,PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoIPage = prodService.pageByCategoryId(page, categoryId);
        return ResponseEntity.ok(productDtoIPage);
    }


    @GetMapping("/prodIds")
    @ApiOperation(value = "商品id", notes = "商品id")
    public ResponseEntity<List<Long>> prodIds() {
        List<Long> list = skuService.listIds();
        return ResponseEntity.ok(list);
    }

    @GetMapping("/prodInfoBySku")
    @ApiOperation(value = "商品详情信息", notes = "根据skuId获取商品信息")
    @ApiImplicitParam(name = "skuId", value = "skuId", required = true, dataType = "Long")
    public ResponseEntity<ProductDto> prodInfoBySku(Long skuId) {
        Sku sku = skuService.getById(skuId);
        Product product = prodService.getProductByProdId(sku.getProdId());

        if (product == null) {
            return ResponseEntity.ok(null);
        }
        Category category = categoryService.getById(product.getCategoryId());
        List<Sku> list = new ArrayList();
        list.add(sku);
        product.setSkuList(list);
        ProductDto productDto = mapperFacade.map(product, ProductDto.class);
        if(Objects.nonNull(category)){
            productDto.setCategoryName(category.getCategoryName());
        }
        // 商品的配送方式
        Product.DeliveryModeVO deliveryModeVO = Json.parseObject(product.getDeliveryMode(), Product.DeliveryModeVO.class);
        // 有店铺配送的方式, 且存在运费模板，才返回运费模板的信息，供前端查阅
        if (deliveryModeVO.getHasShopDelivery()  && product.getDeliveryTemplateId() != null) {
            Transport transportAndAllItems = transportService.getTransportAndAllItems(product.getDeliveryTemplateId());
            productDto.setTransport(transportAndAllItems);
        }

        return ResponseEntity.ok(productDto);
    }

    @PostMapping("/prodInfos")
    @ApiOperation(value = "商品id", notes = "商品id")
    public ResponseEntity<List<Sku>> prodInfos(@RequestBody ProductIdListRequest request) {
        List<Sku> list = skuService.getByIds(request.getList());
        return ResponseEntity.ok(list);
    }

    @GetMapping("/prodInfo")
    @ApiOperation(value = "商品详情信息", notes = "根据商品ID（prodId）获取商品信息")
    @ApiImplicitParam(name = "prodId", value = "商品ID", required = true, dataType = "Long")
    public ResponseEntity<ProductDto> prodInfo(Long prodId) {

        Product product = prodService.getProductByProdId(prodId);
        if (product == null) {
            return ResponseEntity.ok(null);
        }
        Category category = categoryService.getById(product.getCategoryId());

        List<Sku> skuList = skuService.listByProdId(prodId);
        // 启用的sku列表
        List<Sku> useSkuList = skuList.stream().filter(sku -> sku.getStatus() == 1).collect(Collectors.toList());
        product.setSkuList(useSkuList);
        ProductDto productDto = mapperFacade.map(product, ProductDto.class);
        if(Objects.nonNull(category)){
            productDto.setCategoryName(category.getCategoryName());
        }
        // 商品的配送方式
        Product.DeliveryModeVO deliveryModeVO = Json.parseObject(product.getDeliveryMode(), Product.DeliveryModeVO.class);
        // 有店铺配送的方式, 且存在运费模板，才返回运费模板的信息，供前端查阅
        if (deliveryModeVO.getHasShopDelivery()  && product.getDeliveryTemplateId() != null) {
            Transport transportAndAllItems = transportService.getTransportAndAllItems(product.getDeliveryTemplateId());
            productDto.setTransport(transportAndAllItems);
        }

        return ResponseEntity.ok(productDto);
    }

    @GetMapping("/lastedProdPage")
    @ApiOperation(value = "新品推荐", notes = "获取新品推荐商品列表")
    @ApiImplicitParams({
    })
    public ResponseEntity<IPage<ProductDto>> lastedProdPage(PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoIPage = prodService.pageByPutawayTime(page);
        return ResponseEntity.ok(productDtoIPage);
    }

    @GetMapping("/prodListByTagId")
    @ApiOperation(value = "通过分组标签获取商品列表", notes = "通过分组标签id（tagId）获取商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tagId", value = "当前页，默认为1", required = true, dataType = "Long"),
    })
    public ResponseEntity<IPage<ProductDto>> prodListByTagId(
            @RequestParam(value = "tagId") Long tagId,PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoIPage = prodService.pageByTagId(page, tagId);
        return ResponseEntity.ok(productDtoIPage);
    }

    @GetMapping("/moreBuyProdList")
    @ApiOperation(value = "每日疯抢", notes = "获取销量最多的商品列表")
    @ApiImplicitParams({})
    public ResponseEntity<IPage<ProductDto>> moreBuyProdList(PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoIPage = prodService.moreBuyProdList(page);
        return ResponseEntity.ok(productDtoIPage);
    }

    @GetMapping("/tagProdList")
    @ApiOperation(value = "首页所有标签商品接口", notes = "获取首页所有标签商品接口")
    public ResponseEntity<List<TagProductDto>> getTagProdList() {
        List<TagProductDto> productDtoList = prodService.tagProdList();
        return ResponseEntity.ok(productDtoList);
    }

    /**
     * 购物车/立即购买  提交订单,根据店铺拆单
     */
    @PostMapping("/createOrder")
    @ApiOperation(value = "提交订单，返回支付流水号", notes = "根据传入的参数判断是否为购物车提交订单，同时对购物车进行删除，用户开始进行支付")
    public ResponseEntity<OrderResponse> createOrder(@RequestBody CreateOrderRequest mergerOrder) {

        String order = orderService.submit(mergerOrder);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return ResponseEntity.ok(new OrderResponse(sdf.format(new Date()),order));

    }

    /**
     * 购物车/立即购买  提交订单,根据店铺拆单
     */
    @GetMapping("/getLogistics")
    @ApiOperation(value = "提交订单，返回支付流水号", notes = "根据传入的参数判断是否为购物车提交订单，同时对购物车进行删除，用户开始进行支付")
    public ResponseEntity<OrderShipmentResponse> getOrderShipment(String orderNumber) {
        Order order = orderService.getById(orderNumber);

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber());

        Delivery delivery = deliveryService.getById(order.getDvyId());

        OrderShipmentResponse response = new OrderShipmentResponse();
        response.setOrderSn(orderNumber);
        response.setStatus(getStatus(order.getStatus().toString()));
        OrderShipmentResponse.Express express = new OrderShipmentResponse.Express();
        express.setExpressCode(order.getDvyFlowId());
        if(Objects.nonNull(delivery)){
            express.setExpressName(delivery.getDvyName());
        }

        StringBuilder builder = new StringBuilder();
        orderItems.stream().forEach(p->{
            builder.append(p.getSkuId()).append("|");
        });
        express.setItemId(builder.substring(0,builder.toString().length()-1));
        List<OrderShipmentResponse.Express> list = new ArrayList();
        list.add(express);
        response.setExpress(list);
        return ResponseEntity.ok(response);

    }

    private String getStatus(String status){
        if(status2.equals(status)){
            return status3;
        }
        return status1;
    }

}
